const { BrowserWindow, app, globalShortcut, Tray, nativeImage, Menu, dialog, Notification } = require('electron')
const path = require("node:path");
const { Asset, Setting } = require('./db/index.cjs');

Menu.setApplicationMenu(null)
/**
 * @type {import('electron').BrowserWindow}
 */
let win;
/**
 * @type {import('electron').Tray}
 */
let tray;

/**
 * @type {Array<import('electron').BrowserWindow>}
 */
const windows = []

const icon = nativeImage.createFromPath(path.join(__dirname, '..', 'build', 'icons', '64x64.png'));

function createTray() {
	tray = new Tray(icon)
	const menu = Menu.buildFromTemplate([
		{
			label: '退出', click() {
				dialog.showMessageBox({
					type: 'question',
					buttons: ['确认', '取消'],
					detail: '确认退出吗',
					defaultId: 1,
					cancelId: 1
				}).then(({ response }) => {
					if (response === 0) {
						windows.forEach(window => {
							window.close()
							window.destroy()
						})
					}
				})
			}
		}
	]);
	tray.setContextMenu(menu)
	tray.setTitle("资产管理")
	tray.setToolTip("资产管理")
	tray.on('double-click', () => {
		win.show()
	})
}

function createWindow() {
	win = new BrowserWindow({
		width: 1024,
		height: 768,
		show: false,
		icon,
		webPreferences: {
			nodeIntegration: false,
			contextIsolation: true,
			preload: path.join(__dirname, 'preload.cjs')
		}
	});
	windows.push(win)
	if (process.env.NODE_ENV === 'development') {
		win.loadURL(process.env.VITE_DEV_SERVER_URL).then()
	} else {
		win.loadFile('./dist-electron/index.html').then()
	}
	win.on('ready-to-show', () => {
		win.show()
	})
	win.on('close', evt => {
		evt.preventDefault()
		win.hide()
	})
}

function toggleDevTools() {
	win.webContents.toggleDevTools()
}

async function showNotice() {
	const data = await Setting.findOne({ where: { key: 'advanceNoticeDays' } });
	const value = data ? data.dataValues.value : 7
	const num = await Asset.count({
		where: {
			nextTraceabilityDate: {
				[Op.lt]: dayjs().add(Number(value), 'day').toDate()
			}
		}
	})
	if (num > 0) {
		const notification = new Notification({
			title: '溯源提醒',
			body: `有[${num}]个设备待溯源`,
			icon
		});
		notification.show()
	}
}

app.whenReady().then(() => {
	createTray()
	createWindow()
	globalShortcut.register("ctrl + shift + i", () => {
		toggleDevTools()
	})
	showNotice()
})

app.on('window-all-closed', () => {
	if (process.platform !== 'darwin') {
		app.quit()
	}
})

app.on('second-instance', (evt) => {
	evt.preventDefault()
	if (win != null && !win.isDestroyed()) {
		win.show()
	}
})

require('./modules/index.cjs')
const { Op } = require("sequelize");
const dayjs = require("dayjs");
